#include "db.h"

#include <muduo/base/Logging.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <iostream>

std::string MySQL::sm_server{};
std::string MySQL::sm_user{};
std::string MySQL::sm_password{};
std::string MySQL::sm_dbname{};

MySQL::MySQL() {
	m_conn = mysql_init(nullptr);
}

MySQL::~MySQL() {
	if (m_conn != nullptr)
		mysql_close(m_conn);
}

bool MySQL::connect() {
	MYSQL* p = mysql_real_connect(m_conn, sm_server.c_str(), sm_user.c_str(),
		sm_password.c_str(), sm_dbname.c_str(), 3306, nullptr, 0);
	if (p != nullptr) {
		// C和C++代码默认得编码字符是ascii，如果不设置，从MySQL上拉下来得中文显示是???问号
		mysql_query(m_conn, "set names gbk");
		LOG_INFO << "connect mysql success!";
	}
	else {
		LOG_INFO << "connect mysql failed!";
	}
	return p;
}

bool MySQL::update(std::string sql) {
	if (mysql_query(m_conn, sql.c_str())) {
		LOG_INFO << __FILE__ << ":" << __LINE__ << ":" << sql << "更新失败!";
		return false;
	}
	return true;
}

// 查询操作,主要针对select语句
MYSQL_RES* MySQL::query(std::string sql) {
	if (mysql_query(m_conn, sql.c_str())) {
		LOG_INFO << __FILE__ << ":" << __LINE__ << ":" << sql << "查询失败!";
		return nullptr;
	}
	return mysql_use_result(m_conn);
}

MYSQL* MySQL::getConnection() {
	return m_conn;
}

void MySQL::loadConfig()
{
	try {
		boost::property_tree::ptree pt;
		boost::property_tree::ini_parser::read_ini("../config.ini", pt);

		sm_server = pt.get<std::string>("database.server");
		sm_user = pt.get<std::string>("database.user");
		sm_password = pt.get<std::string>("database.password");
		sm_dbname = pt.get<std::string>("database.dbname");
	}
	catch (std::exception& e) {
		std::cerr << "读取数据库配置失败: " << e.what() << std::endl;
	}
}
